import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:icooker/configs/app_configs.dart';
import 'package:icooker/configs/theme/themes.dart';
import 'package:icooker/providers/theme_provider.dart';
import 'package:provider/provider.dart';

import 'configs/api_configs.dart';
import 'configs/routers/routers.dart';
import 'package:flutter_ijkplayer/flutter_ijkplayer.dart';
import 'package:kasax/kasax.dart';

var themeKey;
var isFirstUsed;

void main() {
  GlobalUils.globalInit(() {
    print("renderUICallback: $themeKey");
    runApp(MyApp());
  }, afterRenderUICallback: () {
    print(
        "afterRenderUICallback themeKey: $themeKey , isFirstUsed：$isFirstUsed");
    // 浸沉式状态栏
    if (Platform.isAndroid) {
      // 以下两行 设置android状态栏为透明的沉浸。写在组件渲染之后，是为了在渲染后进行
      // set赋值，覆盖状态栏，写在渲染之前MaterialApp组件会覆盖掉这个值。
      SystemUiOverlayStyle systemUiOverlayStyle =
          SystemUiOverlayStyle(statusBarColor: Colors.transparent);
      SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    }
  }, beforeRenderUICallback: () {
    print(
        "pre exec beforeRenderUICallback themeKey: $themeKey , isFirstUsed：$isFirstUsed");
    doInit();
    print(
        "end exec beforeRenderUICallback themeKey: $themeKey , isFirstUsed：$isFirstUsed");
  });
}

doInit() async {
  // IjkConfig.isLog = true;
//  IjkConfig.level = LogLevel.verbose;
  await IjkManager.initIJKPlayer();

  themeKey = await SPUtils.take(AppConfigs.KEY_THEME_DATA, "");
  print("themeKey: $themeKey");
  isFirstUsed = await SPUtils.take(AppConfigs.KEY_FIRST_USED_DATA, true);
  print("isFirstUsed: $isFirstUsed");

  /// 初始化网络引擎
  DioManager.config(baseUrl: ApiConfigs.BASE_URL);
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // 默认为蓝色
    ThemeData _themeData;
    print("_MyAppState build themeKey: $themeKey , isFirstUsed：$isFirstUsed");
    if (themeKey != null && themeKey.isNotEmpty) {
      var cachedThemeRes = themeColor[themeKey];
      _themeData = ThemeData(
        primaryColor: cachedThemeRes['primaryColor'],
        primaryColorDark: cachedThemeRes['primaryColorDark'],
        accentColor: cachedThemeRes['accentColor'],
        primaryColorLight: cachedThemeRes['primaryColorLight'],
      );
    } else {
      _themeData = buildDefaultThemeData();
    }

    return buildMultiProvider(_themeData);
  }

  MultiProvider buildMultiProvider(ThemeData _themeData) {
    return MultiProvider(
      providers: [ChangeNotifierProvider.value(value: AppThemeProvider())],
      // 提供provider
      child: Consumer<AppThemeProvider>(
        /// 变化监听
        builder: (context, provider, child) {
          if (provider.themeColor != null && provider.themeColor.isNotEmpty) {
            var changeThemeRes = themeColor[provider.themeColor];
            _themeData = ThemeData(
              primaryColor: changeThemeRes['primaryColor'],
              primaryColorDark: changeThemeRes['primaryColorDark'],
              accentColor: changeThemeRes['accentColor'],
              primaryColorLight: changeThemeRes['primaryColorLight'],
            );
          }
          return ScreenUtilInit(
            designSize: Size(335, 667),
            builder: () => MaterialApp(
              initialRoute: (isFirstUsed == null || isFirstUsed == true)
                  ? '/'
                  : '/splash',
              theme: _themeData,
              routes: routers,
              onGenerateRoute: onGenerateRoute,
            ),
          );
        },
      ),
    );
  }

  /// 构建默认主题
  ThemeData buildDefaultThemeData() {
    var defThemeResource = themeColor['blue'];
    ThemeData _themeData = ThemeData(
        primaryColor: defThemeResource['primaryColor'],
        primaryColorDark: defThemeResource['primaryColorDark'],
        accentColor: defThemeResource['accentColor'],
        primaryColorLight: defThemeResource['primaryColorLight'],
        indicatorColor: Colors.white);
    return _themeData;
  }
}
